<template>
  <div class="table-search" :class="{ 'table-search-simple': mode === 1 }">
    <schema-form ref="dynamicFormRef" :form-schema="formSchema">
      <template #operate-button>
        <span class="search-submitButtons" :class="{ 'search-submitButtons-simple': mode === 1 }">
          <span>
            <a-button style="margin-right: 10px" @click="reset" :type="resetBtnType">
              {{ $t("common.resetText") }}
            </a-button>
            <a-button :type="searchBtnType" @click="query"> {{ $t("common.queryText") }} </a-button>
          </span>
          <template v-if="formItemSchemas.length > 0 && formItemSchemas.length > defaultShowItems">
            <a style="margin-left: 8px" @click="toggleAdvanced">
              {{ advanced? $t("component.form.putAway"): $t("component.form.unfold") }}
              <DownOutlined class="collapse-icon" />
            </a>
          </template>
        </span>
      </template>
    </schema-form>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, inject, nextTick, PropType, reactive, ref, toRefs } from "vue";
import { DownOutlined } from "@ant-design/icons-vue";
import type { TableColumn } from "../../typing";
import SchemaForm from "@/framework/components/core/schema-form/schema-form.vue";
import type { FormItemSchema, FormSchema } from "@/framework/components/core/schema-form/types/form";
import { dict } from "@/framework/core/dict";
import { LayoutMode } from "@/framework/components/core/super-table/props";

export default defineComponent({
  name: "NewQueryForm",
  components: { DownOutlined, SchemaForm },
  props: {
    /** 默认显示个数 */
    defaultShowItems: {
      type: Number,
      default: 3
    },
    /** 表单属性配置 */
    formProps: {
      type: Object as PropType<FormSchema>,
      default: () => ({})
    },
    columns: {
      type: Object as PropType<TableColumn[]>,
      required: true
    },
    searchBtnType: {
      type: String,
      default: 'primary'
    },
    resetBtnType: {
      type: String,
      default: 'default'
    }
  },
  emits: ["query", "reset", "toggle-advanced"],
  setup(props, { slots, emit }) {
    const state = reactive({
      advanced: false,
      labelMap: {}
    });
    const mode = inject("layoutMode") as Number;
    console.log("mode", mode);
    const dynamicFormRef = ref<InstanceType<typeof SchemaForm>>();

    // 获取表格列key
    const getColumnKey = (column: TableColumn) => {
      return `${column.field || ""}`.split(".").pop() || "";
    };

    /**
     * @description 展开/收起 图标旋转转数
     */
    const turn = computed(() => `${state.advanced ? 0.5 : 0}turn`);

    const formSchema = computed(() => {
      const result = {
        schemas: !state.advanced
          ? formItemSchemas.value.slice(0, props.defaultShowItems)
          : formItemSchemas.value,
        labelWidth: 80,
        ...props.formProps
      };
      if (mode === LayoutMode.SIMPLE) {
        result.labelCol = { span: 0 };
      }
      return result;
    });

    const formItemSchemas = computed<FormItemSchema[]>(() => {
      let result = props.columns
        .filter((n) => {
          const field = getColumnKey(n);
          return !n.hideInSearch && n.type != "seq" && !!field && field !== "$action";
        })
        .map((n) => {
          if (n.dict) {

            if (!n.formItemProps?.component || n.formItemProps?.component == "Select") {
              return {
                field: n.formItemProps?.field ?? n.searchField ?? getColumnKey(n),
                component: "Select",
                componentProps: {
                  options: dict.get(n.dict).map(item => {
                    return { value: item.value, label: item.name };
                  })
                },
                label: n.title,
                colProps: { // TODO 考虑响应式布局
                  span: Math.floor(24 / props.defaultShowItems)
                },
                ...n.formItemProps
              } as FormItemSchema;
            }
            if (n?.formItemProps?.component == "RadioGroup") {

            }
          }
          return {
            field: n.formItemProps?.field ?? n.searchField ?? getColumnKey(n),
            component: "Input",
            label: n.title,
            colProps: { // TODO 考虑响应式布局
              span: Math.floor(24 / props.defaultShowItems)
            },
            ...n.formItemProps
          };
        });
      console.log("formItemSchemas", result)
      console.log("formItemSchemas", props.defaultShowItems)
      return result;
    });

    /**
     * @description 切换展开/收起 状态
     */
    const toggleAdvanced = async () => {
      state.advanced = !state.advanced;
      await nextTick();
      emit("toggle-advanced", state.advanced);
    };

    /**
     * @param {number} span 栅格占位格数
     */
    const calcSubBtnOffset = (span: number) => {
      const total = (state.advanced ? Object.keys(slots).length : props.defaultShowItems) * span;
      const remainder = total % 24;
      if (total < 24 || remainder === 0) {
        return 0;
      }
      return 24 - remainder;
    };

    const reset = async () => {
      dynamicFormRef.value?.resetFields();
      await query();
    };
    const query = async () => {
      const formModel = await dynamicFormRef.value?.validate();
      console.log("queryParams", formModel);

      emit("query", formModel);
    };

    const getFormModel = () => {
      const formModel = dynamicFormRef.value?.formModel;
      return formModel;
    };

    return {
      ...toRefs(state),
      mode,
      dynamicFormRef,
      turn,
      reset,
      query,
      calcSubBtnOffset,
      formSchema,
      formItemSchemas,
      toggleAdvanced,
      getFormModel
    };
  }
});
</script>

<style lang="less" scoped>
.table-search {
  margin-bottom: 16px;
  padding: 24px 24px 0;
  background: #fff;
}

.table-search-simple {
  padding: 0 !important;
  margin-bottom: 0px;
  line-height: 100%;
}

.table-search-simple:deep(.ant-form-item) {
  margin-bottom: 0px !important;
}

.table-search-simple:deep(.ant-form-item-label label) {
  display: none;
}

.search-submitButtons {
  display: block;
  margin-bottom: 24px;
  white-space: nowrap;
  float: right;
  overflow: hidden;
}

.search-submitButtons-simple {
  margin-bottom: 0px !important;
  float: unset !important;
}

:deep(.ant-row) {
  width: 100%;
}

:deep(.ant-form-item) {
  margin-right: 0;

  &.operate-button {
    margin-bottom: 0;
  }
}

.collapse-icon {
  transform: rotate(v-bind(turn));
  transition: transform 0.3s;
}
</style>
